<template>
  <view class="container">
    <view class="gold-block">
      <view class="title">提现金额</view>
      <view class="input-block">
        <text>￥</text>
        <input 
          @input="onKeyInput" 
          v-model="inputMoney" 
          placeholder="输入金额" 
          type="digit"
          @blur="formatInputMoney"
        />
      </view>
      <view class="balance">当前账户余额{{money}}元，可提现金额{{drawmoney}}元</view>
      <view class="tips" :style="{ color: inputMoney && isValidMoney ? '#999' : '#f56c6c' }">
        {{ tipsText }}
      </view>
      <van-button 
        class="_btn" 
        type="primary" 
        color="#3c91ff" 
        round 
        @click="withdrawalClick"
        :disabled="!isValidMoney"
      >
        {{isConfirm ? '确认收款' : '去提现'}}
      </van-button>
    </view>

    <!-- 确认弹窗 -->
    <view v-if="showConfirmModal" class="confirm-modal">
      <view class="modal-content">
        <view class="modal-title">确认收款</view>
        <view class="modal-amount">￥{{confirmAmount}}元</view>
        <view class="modal-desc">来自校园车队的转账</view>
        <view class="modal-buttons">
          <van-button @click="confirmTransfer" type="primary" color="#3c91ff">确认收款</van-button>
          <van-button @click="closeConfirmModal">取消</van-button>
        </view>
      </view>
    </view>

    <view class="detail-block">
      <van-cell @click="toFundsDetail" size="large" title="资金明细" icon="records-o" is-link />
      <van-cell @click="toCommission" size="large" title="佣金比例" icon="cashier-o" is-link />
    </view>
  </view>
</template>

<script setup>
  import {
    ref,
    watch
  } from 'vue';
  import {
    onLoad
  } from '@dcloudio/uni-app';
  import {
    getUserMoney,
    withdrawSubmit
  } from '@/api/index.js';
  import {
    tiXian,
    getTransferInfo,
    getTiXianAndDongJie,
    addLiuShuiDelYuEr,
    chaXunPeiZhiHeGe
  } from '@/api/xiaoquan.js';

  // 状态管理
  const money = ref('0.00');
  const drawmoney = ref('0.00');
  const inputMoney = ref(''); // 用户输入的原始值
  const formattedMoney = ref(''); // 格式化后的值
  const isConfirm = ref(false); // 是否显示确认界面
  const showConfirmModal = ref(false); // 确认弹窗状态
  const confirmAmount = ref('0'); // 确认金额
  const transferPackage = ref(''); // 转账package信息
  const mchId = ref('1704770546'); // 商户号（请替换为真实值）
  const appId = ref('wx37fc00234f288b15'); // 商户AppID（请替换为真实值）
  const isValidMoney = ref(true); // 金额是否有效
  const tipsText = ref(''); // 提示文本
  
  // 最小提现金额（单位：元）
  const MIN_WITHDRAW_AMOUNT = 0.3;
  
  // 正则表达式：允许0-9的数字和最多一个小数点，小数点后最多两位
  const moneyRegExp = /^(0|[1-9]\d*)(\.\d{0,2})?$/;

  // 格式化金额
  const formatInputMoney = () => {
    let value = inputMoney.value;
    
    if (!value) {
      formattedMoney.value = '';
      isValidMoney.value = true;
      tipsText.value = '请输入提现金额';
      return;
    }
    
    // 基础格式化：只保留数字和小数点
    value = value.replace(/[^\d.]/g, '');
    
    // 处理多个小数点的情况
    const parts = value.split('.');
    if (parts.length > 2) {
      value = parts[0] + '.' + parts[1];
    }
    
    // 限制小数点后最多两位
    if (value.indexOf('.') > -1) {
      value = value.substring(0, value.indexOf('.') + 3);
    }
    
    // 去除前导零（保留0.xx的情况）
    if (value.startsWith('0') && value.length > 1 && value.charAt(1) !== '.') {
      value = value.replace(/^0+/, '');
    }
    
    // 更新格式化后的值
    formattedMoney.value = value;
    
    // 验证金额格式
    isValidMoney.value = moneyRegExp.test(value);
    
    if (!isValidMoney.value) {
      tipsText.value = '请输入正确的金额格式';
    } else if (parseFloat(value) < MIN_WITHDRAW_AMOUNT) {
      tipsText.value = `最低提现金额为${MIN_WITHDRAW_AMOUNT}元`;
      isValidMoney.value = false;
    } else if (parseFloat(value) > parseFloat(drawmoney.value)) {
      tipsText.value = '提现金额不能超过可提现余额';
      isValidMoney.value = false;
    } else {
      tipsText.value = '可提现金额必须为数字，最多两位小数';
    }
    
    // 更新确认金额
    confirmAmount.value = value;
  }

  // 输入事件处理
  const onKeyInput = (event) => {
    inputMoney.value = event.target.value;
    formatInputMoney();
  }

  // 页面跳转
  const toFundsDetail = () => {
    uni.navigateTo({
      url: "/package/pages/zijinliushui/zijinliushui"
    })
  }

  const toCommission = () => {
    uni.navigateTo({
      url: "/package/pages/yong_jin_bi_li/yong_jin_bi_li"
    })
  }

  // 提现操作 - 集中进行金额验证
  const withdrawalClick = async () => {
    const value = formattedMoney.value;

    // 验证处理后的金额
    if (!value || parseFloat(value) <= 0) {
      uni.showToast({
        title: '请输入有效提现金额',
        duration: 1000,
        icon: 'none'
      });
      return;
    }

    // 检查最低提现金额
    if (parseFloat(value) < MIN_WITHDRAW_AMOUNT) {
      uni.showToast({
        title: `最低提现金额为${MIN_WITHDRAW_AMOUNT}元`,
        duration: 1000,
        icon: 'none'
      });
      return;
    }

    // 检查是否超过可提现金额
    if (parseFloat(value) > parseFloat(drawmoney.value)) {
      uni.showToast({
        title: '没有足够余额可提现',
        duration: 1000,
        icon: 'none'
      });
      return;
    }

    // 新增一次点击提交，查询点击提交的次数是否超额，查询一次最多提现的金额是否超额，查询一天是否提现超额
    let ares = await chaXunPeiZhiHeGe(value);
    if (ares.data.isTiXian == false) {
      // 今日不可提现
      uni.showToast({
        title: ares.data.message,
        duration: 2000,
        icon: 'none'
      });
      return;
    }

    console.log('准备提现:', value)
    confirmAmount.value = value;
    
    // 显示确认弹窗
    showConfirmModal.value = true;
  }

  // 确认收款
  const confirmTransfer = () => {
    closeConfirmModal(); // 关闭弹窗

    if (uni.canIUse('requestMerchantTransfer')) {
      // 这里应该从接口获取package信息，而不是使用硬编码
      tiXian(formattedMoney.value).then((res) => {
        console.log('提现接口返回:', res);
        
        if (!res.data || !res.data.packageInfo) {
          uni.showToast({
            title: '提现失败，请稍后再试',
            duration: 1500,
            icon: 'none'
          });
          return;
        }
        
        uni.requestMerchantTransfer({
          mchId: mchId.value,
          appId: appId.value,
          package: res.data.packageInfo,
          success: async (res) => {
            console.log('确认收款成功', res);
            
            // 处理流水和余额
            await queRenShouKuan();
            
            uni.showToast({
              title: '提现成功',
              icon: 'success',
              duration: 1500
            });
            
            setTimeout(() => {
              // 返回上一页或跳转到资金明细页
              uni.navigateBack();
            }, 1500);
          },
          fail: (res) => {
            console.error('确认收款失败', res);
            uni.showToast({
              title: '收款确认失败，请稍后再试',
              duration: 1500,
              icon: 'none'
            });
          },
          complete: () => {
            isConfirm.value = false;
            transferPackage.value = '';
          }
        });
      }).catch(err => {
        console.error('提现接口错误:', err);
        uni.showToast({
          title: '网络错误，请稍后再试',
          duration: 1500,
          icon: 'none'
        });
      });
    } else {
      uni.showModal({
        content: '你的微信版本过低，请更新至最新版本。',
        showCancel: false,
      });
    }
  }

  const queRenShouKuan = async () => {
    try {
      console.log('更新流水和余额:', formattedMoney.value);
      await addLiuShuiDelYuEr(formattedMoney.value);
      
      // 刷新余额
      getTiXianAndDongJie().then(res => {
        money.value = res.data.zongJin || '0.00';
        drawmoney.value = res.data.tiXianJin || '0.00';
      });
    } catch (err) {
      console.error('更新流水失败:', err);
      // 可以考虑添加失败处理逻辑
    }
  }
  
  // 关闭确认弹窗
  const closeConfirmModal = () => {
    showConfirmModal.value = false;
  }

  // 页面加载
  onLoad(() => {
    getTiXianAndDongJie().then(res => {
      console.log('账户余额接口返回:', res);
      money.value = res.data.zongJin || '0.00';
      drawmoney.value = res.data.tiXianJin || '0.00';
    });
  })

  // 初始化提示文本
  watch(drawmoney, () => {
    tipsText.value = '可提现金额必须为数字，最多两位小数';
  }, { immediate: true });
</script>

<style scoped>
  .container {
    min-height: 100vh;
    width: 100%;
    background-color: #f8fbff;
  }

  .gold-block {
    height: 380rpx;
    background-color: #fff;
    width: calc(100% - 40rpx);
    padding-left: 30rpx;
    padding-right: 30rpx;
    display: flex;
    flex-direction: column;
    justify-content: center;
    gap: 20rpx;
    position: relative;
  }

  .gold-block .title {
    font-weight: bold;
    font-size: 32rpx;
  }

  .gold-block .input-block {
    display: flex;
    font-size: 40rpx;
    width: 61%;
    padding: 10rpx 0;
  }
  
  .gold-block .input-block text {
    margin-right: 10rpx;
    color: #333;
  }
  
  .gold-block .input-block input {
    flex: 1;
    font-size: 40rpx;
    color: #333;
  }

  .gold-block .balance {
    color: #999999;
    font-size: 26rpx;
    margin-top: 10rpx;
  }
  
  .gold-block .tips {
    font-size: 24rpx;
    margin-top: 5rpx;
  }

  ._btn {
     position: absolute;
     right: 30rpx;
     bottom: 47%;
     width: 200rpx;
  }

  /* 确认弹窗样式 */
  .confirm-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 999;
  }

  .modal-content {
    background-color: #fff;
    border-radius: 20rpx;
    padding: 40rpx;
    width: 80%;
    max-width: 600rpx;
    text-align: center;
  }

  .modal-title {
    font-size: 36rpx;
    font-weight: bold;
    margin-bottom: 30rpx;
  }

  .modal-amount {
    font-size: 60rpx;
    font-weight: bold;
    color: #e64340;
    margin: 20rpx 0;
  }

  .modal-desc {
    font-size: 28rpx;
    color: #666;
    margin-bottom: 40rpx;
  }

  .modal-buttons {
    display: flex;
    justify-content: space-between;
    margin-top: 30rpx;
  }

  .modal-buttons .van-button {
    flex: 1;
    margin: 0 10rpx;
  }

  .detail-block {
    margin-top: 30rpx;
    background-color: #fff;
    padding: 20rpx 30rpx;
  }
</style>